package com.shao.pojo;

import java.awt.event.FocusEvent;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: SJP
 * Date: 2021/5/24
 * Time: 19:35
 * Description: No Description
 */
public class Cart {
   // private Integer totalCount;
   // private BigDecimal totalPrice;
    /**
     * key是商品编号
     * value是商品信息
     */
    private Map<Integer,CartItem> items = new LinkedHashMap<>();

    /**
     * 添加商品项
     * @param cartItem
     */
    public void addItem(CartItem cartItem){
        //通过商品id遍历map查询是否有相同商品信息
         CartItem item = items.get(cartItem.getId());
         if(item ==null){
             items.put(cartItem.getId(),cartItem);
         }else {
             item.setCount(item.getCount()+1);
             item.setTotalPrice(item.getPrice().multiply(new BigDecimal(item.getCount())));
         }
    }
    /**
     * 删除商品项
     * @param id
     */
    public void deleteItem(Integer id){
        items.remove(id);
    }
    /**
     * 修改商品数量
     * @param id
     */
    public void updateItem(Integer id,Integer count){
        //先查看购物车是否有此商品，如果有则进行修改，更新总金额
        CartItem cartItem = items.get(id);
        if(cartItem != null){
            cartItem.setCount(count);
            cartItem.setTotalPrice(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())));
        }

    }
    /**
     * 删除购物车所有
     */
    public void deleteItems(){
        items.clear();
    }
    public Integer getTotalCount(){
        Integer totalCount = 0;
        for(Map.Entry<Integer,CartItem>entry:items.entrySet()){

            totalCount  = entry.getValue().getCount();
        }
        return totalCount;
    }
    public BigDecimal getTotalPrice(){
       BigDecimal totalPrice = new BigDecimal(0);
        for(Map.Entry<Integer,CartItem>entry:items.entrySet()){
          totalPrice.add(entry.getValue().getTotalPrice());
        }
        return totalPrice;
    }

    public Cart() {
    }

    public Cart( Map<Integer, CartItem> items) {
        this.items = items;
    }

    /**
     * 获取
     * @return items
     */
    public Map<Integer, CartItem> getItems() {
        return items;
    }

    /**
     * 设置
     * @param items
     */
    public void setItems(Map<Integer, CartItem> items) {
        this.items = items;
    }

    public String toString() {
        return "Cart{totalCount = " + getTotalCount() + ", totalPrice = " + getTotalPrice() + ", items = " + items + "}";
    }
}
